<?php
namespace app\nadmin\controller;
use think\Controller;
use think\facade\Validate;
use think\Db;

/**
 * @explain 杂项操作类
 */

class Sundry extends Controller
{
    //当前模块
    protected $module = 'nadmin';
    //错误信息
    protected $errorMsg = "";
    //无权限页面
    public function nopower()
    {
        return $this->fetch("sundry/nopower");
    }

    //初始化页面
    public function initpage()
    {
        //查看是否已配置数据库数据
        if(file_exists($this->databaseConfFilename()))
        {
            $dataBase = include $this->databaseConfFilename();
            $dataBase['charset'] = $this->unGetCharset($dataBase['charset']);
            $dataBase['type'] = $this->unGetType($dataBase['type']);
            $this->assign("dataBase",$dataBase);
        }
        return $this->fetch('sundry/initpage');
    }

    //添加数据库参数配置
    public function addDatabaseConf()
    {
        $type = $this->request->type;
        $hostname = $this->request->hostname;
        $database = $this->request->database;
        $username = $this->request->username;
        $password = $this->request->password;
        $hostport = $this->request->hostport;
        $charset = $this->request->charset;

        //验证数据格式
        $rule = [
            'type' => 'require|in:1,2,3,4',
            'hostname' => 'require|max:100',
            'database' => 'require|chsDash|max:50',
            'username' => 'require|chsDash|max:50',
            'password' => 'require|chsDash|max:50',
            'hostport' => 'require|between:0,65535',
            'charset' => 'require|in:1,2',
        ];

        $data = compact('type', 'hostname', 'database', 'username', 'password', 'hostport', 'charset');
        $validate = Validate::make($rule, []);
        if (!$validate->check($data)) {
            return echojson($validate->getError(), 0);
        }

        //加上前缀
        $data['prefix'] = $data['database'].'_';
        $data['type'] = $this->getType($data['type']); //数据库类型
        $data['charset'] = $this->getCharset($data['charset']); //编码

        //尝试连接数据库
        if(!$this->connectDb($data))
        {
            return echojson($this->errorMsg,0);
        };

        //写配置
        if ($this->writeConf($data)) {
            return echojson("success", 1);
        } else {
            return echojson("数据库配置写入失败", 0);
        }
    }

    //数据库配置写入  param $data [] 写入的配置数据
    protected function writeConf($data)
    {
        if (is_array($data) && $data)
        {

            $str = "<?php" . PHP_EOL;
            $str .= "/*************模块".$this->getModule()."数据库配置************/".PHP_EOL;
            $str .= "return [".PHP_EOL;
            foreach($data as $k=>$v)
            {
                $str .= $this->getAnnotation($k).PHP_EOL;  //注释
                $str .= "   '$k' => '$v',".PHP_EOL;
            }
            $str .= "];".PHP_EOL;

            /*if(file_exists($this->databaseConfFilename()))
            {
                $oldData =  file_get_contents($this->databaseConfFilename());

                if($str == $oldData)
                {
                    //数据未变化
                    return true;
                };
            }*/

            $re = file_put_contents($this->databaseConfFilename(),$str);

            if($re)
            {
                return true;
            }else{
                return false;
            }
        }
        return false;
    }

    //数据库配置文件地址
    protected function databaseConfFilename()
    {
        //检测目录是否存在，若不存在则创建目录
        $dirName = dirname(dirname(dirname(__DIR__)))."\config\\".$this->getModule();
        $dirName = $this->checkDir($dirName);
        $filename = $dirName."\\database.php";
        return $filename;
    }

    /*
     * @explain  检测目录是否存在，若不存在则创建目录
     * @param $dirName string 目录
     */
    protected function checkDir($dirName)
    {
        if(!is_dir($dirName))
        {
            mkdir($dirName);  //无论目录创建是否成功，最后都交与文件写入判断结果
        }
        return $dirName;
    }

    /*获取当前模块*/
    protected function getModule()
    {
        return request()->module() ? request()->module() :  $this->module;
    }

    /*
     * @explain 返回数据库配置对应的注释
     * @param $k string 对应的下标
     */
    protected function getAnnotation($k)
    {
        if($k == 'type')
        {
            return "    //数据库类型";
        }elseif($k == 'hostname'){
            return "    //服务器地址";
        }elseif($k == 'database'){
            return "    //数据库名";
        }elseif($k == 'username'){
            return "    //用户名";
        }elseif($k == 'password'){
            return "    //密码";
        }elseif($k == 'hostport'){
            return "    //端口";
        }elseif($k == 'charset'){
            return "    //数据库编码";
        }elseif($k == 'prefix')
        {
            return "    //前缀";
        }
    }

    /*
     * @explain 数据库编码数据转换
     * @param $param int
     * @return 编码 string
     */
    protected function getCharset($param)
    {
        switch($param)
        {
            case 1:
                return "utf8";
            break;
            case 2:
                return "gbk";
            break;
        }
    }

    /*
     * @explain 反转数据库编码数据转换
     * @param $param int
     * @return 编码 string
     */
    protected function unGetCharset($param)
    {
        $param = strtolower($param);
        if($param == "utf8")
        {
            return 1;
        }elseif($param == "gbk")
        {
            return 2;
        }
    }

    /*
     * @explain 数据库类型数据转换
     * @param $param int
     * @return 数据库类型 string
     */
    protected function getType($param)
    {
        switch($param)
        {
            case 1:
                return "mysql";
                break;
            case 2:
                return "sqlite";
                break;
            case 3:
                return "pgsql";
                break;
            case 4:
                return "sqlserver";
                break;
        }
    }

    /*
     * @explain 反转数据库类型数据转换
     * @param $param int
     * @return 数据库类型 string
     */
    protected function unGetType($param)
    {
        $param = strtolower($param);
        if($param == 'mysql')
        {
            return 1;
        }elseif($param == 'sqlite')
        {
            return 2;
        }elseif($param == 'pgsql')
        {
            return 3;
        }elseif($param == 'sqlserver')
        {
            return 4;
        }
    }

    /*
     * @explian 添加初始化超级管理员
     */
    public function addAdminer()
    {
        $username ="adminer"; //$this->request->username;
        $pwd ="adminer";// $this->request->pwd;

        //验证数据
        $rule = [
            'username'=> 'require|alphaDash|min:6|max:12', //汉字字母数字下划线
            'pwd' =>'require|alphaDash|min:6|max:12', //字母数字下划线
        ];
        $msg = [
            'username.require' => '账号不能为空',
            'username.alphaDash' => '账号必须是字母\数字\下划线',
            'username.min'=>'账号长度不能少于6位',
            'username.max'=>'账号长度不能大于12位',
            'pwd.require' => '账号不能为空',
            'pwd.alphaDash' => '账号必须是字母\数字\下划线',
            'pwd.min'=>'账号长度不能少于6位',
            'pwd.max'=>'账号长度不能大于12位',
        ];
        $data = compact('username','pwd');
        $validate = Validate::make($rule,$msg);
        if(!$validate->check($data))
        {
            return echojson($validate->getError(),0);
        }

        //添加数据
        $createInit = new Createinit();
        $createInit->username = $username;
        $createInit->pwd = $pwd;

        $re = $createInit->createInit();

        if($re){
            return echojson("管理员账号注册成功，请前往管理员中心完善资料",1);
        }else{
            return echojson($createInit->errorMsg,0);
        }
    }



    //尝试连接数据库，判断数据库配置是否填写正确
    protected function connectDb($data)
    {
        try{
            //通过执行一个SQL语句检测数据库连接是否异常
            Db::connect($data)->query("show databases");
            return true;
        }catch(\Exception $e){
            $this->errorMsg = $e->getMessage();
            return false;
        }
    }
}